package services

import (
	"GOPAAS/configs/config"
	"GOPAAS/internal/app/model"
	"GOPAAS/tools/jiguang"
	"encoding/json"
)

type JguangService struct {
	AppKey       string
	MasterSecret string
}

func GetJguangService() *JguangService {
	return &JguangService{
		AppKey:       config.Conf.Jiguang.AppKey,
		MasterSecret: config.Conf.Jiguang.MasterSecret,
	}
}

// FastLogin 一键登录
func (j *JguangService) FastLogin(loginToken string, client_type string) (res string, err error) {
	jg := jiguang.New(j.AppKey, j.MasterSecret)
	res, err = jg.GetPhone(loginToken, client_type)
	return
}

type PushData = map[string]interface{}

func PushToUser(user_ids []int64, title string, msg string, extras map[string]interface{}, cid string) (err error) {
	jg_service := GetJguangService()
	var registration_ids []string
	db.Model(&model.ResUsers{}).Where("id in ?", user_ids).Where("registration_id is not null").Pluck("registration_id", &registration_ids)
	if len(registration_ids) > 0 {
		err = jg_service.Push(registration_ids, title, msg, extras, cid)
	}
	return
}

// Push 推送
func (j *JguangService) Push(registration_id []string, title string, msg string, extras map[string]interface{}, cid string) (err error) {
	var data = make(PushData, 0)
	if cid != "" {
		data["cid"] = cid
	}
	//平台
	data["platform"] = "all"                                                      //平台
	data["audience"] = map[string]interface{}{"registration_id": registration_id} //推送目标
	data["notification"] = map[string]interface{}{
		"alert": msg,
		"android": map[string]interface{}{
			"alert": msg,
			"title": title,
			//"builder_id":   3,//通知栏样式 ID
			//"style":        1, // 1,2,3 用来指定通知栏样式类型，默认为 0。1-bigText,2-Inbox,3-bigPicture
			//"channel_id":        1, //android 通知 channel_id
			//"alert_type":   1, // -1 ~ 7 通知提醒方式
			//"big_text":     "big text content",// 大文本通知栏样式
			//"inbox":        JSONObject,
			//"big_pic_path": "picture url",
			//"priority":     0, // -2~2 通知栏展示优先级
			//"category":     "category str",
			"extras": extras,
		},
		"ios": map[string]interface{}{
			"alert":  msg,
			"badge":  "+1",
			"extras": extras,
		},
	}
	data["options"] = map[string]interface{}{
		"apns_production": false, //开发模式
	}
	jg := jiguang.New(j.AppKey, j.MasterSecret)
	_, err = jg.PushV3(data)
	return
}

type CidList struct {
	Cidlist []string `json:"cidlist"`
}

func (j *JguangService) GetCid() (result string, err error) {
	jg := jiguang.New(j.AppKey, j.MasterSecret)
	body, err := jg.GetCid(1)
	if err != nil {
		return
	}
	var cid_list CidList
	json.Unmarshal(body, &cid_list)
	return cid_list.Cidlist[0], nil
}
